<script lang="ts" setup>
import type { NotificationItem } from '@vben/layouts';

import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { AuthenticationLoginExpiredModal, useVbenModal } from '@vben/common-ui';
import { useWatermark } from '@vben/hooks';
import { ProfileIcon } from '@vben/icons';
import {
  BasicLayout,
  LockScreen,
  Notification,
  UserDropdown,
} from '@vben/layouts';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';

import { listMessage } from '#/api/system/sysmessage/own';
import { $t } from '#/locales';
import { useAuthStore, useXTenantStore } from '#/store';
import LoginForm from '#/views/_core/authentication/login.vue';

import Form from './component/switchTenant.vue';

/**
 * {
    avatar: 'https://avatar.vercel.sh/vercel.svg?text=VB',
    date: '3小时前',
    isRead: true,
    message: '描述信息描述信息描述信息',
    title: '收到了 14 份新周报',
  }
 */
const notifications = ref<NotificationItem[]>([]);

const userStore = useUserStore();
const authStore = useAuthStore();
const xtenantStore = useXTenantStore();
const accessStore = useAccessStore();
const router = useRouter();

const { destroyWatermark, updateWatermark } = useWatermark();
const showDot = computed(() =>
  notifications.value.some((item) => !item.isRead),
);

const menus = computed(() => [
  {
    handler: () => {
      router.push('/user_profile');
    },
    icon: ProfileIcon,
    text: $t('user.profile'),
  },
]);

const avatar = computed(() => {
  return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
});

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

async function handleLogout() {
  await authStore.logout();
}

function handleNoticeClear() {
  notifications.value = [];
}

function handleMakeAll() {
  notifications.value.forEach((item) => (item.isRead = true));
}

watch(
  () => preferences.app.watermark,
  async (enable) => {
    if (enable) {
      await updateWatermark({
        content: `${userStore.userInfo?.username} - ${userStore.userInfo?.realName}`,
      });
    } else {
      destroyWatermark();
    }
  },
  {
    immediate: true,
  },
);

/**
 * 公告查询
 */
async function listAnnouncement() {
  const list = await listMessage();
  notifications.value = list.rows.map((option) => {
    return {
      avatar: 'https://avatar.vercel.sh/vercel.svg?text=msg',
      date: option.createAt,
      isRead: true,
      message: option.content,
      title: option.title,
    };
  });
}

listAnnouncement();
</script>

<template>
  <FormModal />
  <BasicLayout @clear-preferences-and-logout="handleLogout">
    <!-- 控制 Logo 插槽 -->
    <template #logo-text v-if="userStore.userInfo?.superTenant">
      <span
        :style="{
          cursor: 'pointer',
          fontSize: '12px',
        }"
        @click="formModalApi.open()"
      >
        切换租户 > {{ xtenantStore.xtenantName ?? $t('tenant.superTenant') }}
      </span>
    </template>
    <template #user-dropdown>
      <UserDropdown
        :avatar
        :menus
        :text="userStore.userInfo?.username"
        :description="userStore.userInfo?.admin ? $t('user.superadmin') : ''"
        tag-text="Pro"
        @logout="handleLogout"
      />
    </template>
    <template #notification>
      <Notification
        :dot="showDot"
        :notifications="notifications"
        @clear="handleNoticeClear"
        @make-all="handleMakeAll"
      />
    </template>
    <template #extra>
      <AuthenticationLoginExpiredModal
        v-model:open="accessStore.loginExpired"
        :avatar
      >
        <LoginForm />
      </AuthenticationLoginExpiredModal>
    </template>
    <template #lock-screen>
      <LockScreen :avatar @to-login="handleLogout" />
    </template>
  </BasicLayout>
</template>
